package com.woniuxy.yoga.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.yoga.business.dao.mapper.BusinessAccountMapper;
import com.woniuxy.yoga.business.dao.mapper.BusinessPaymentMapper;
import com.woniuxy.yoga.business.dao.mapper.BusinessStoreMapper;
import com.woniuxy.yoga.business.dao.model.BusinessAccount;
import com.woniuxy.yoga.business.dao.model.BusinessPayment;
import com.woniuxy.yoga.business.dao.model.BusinessStore;
import com.woniuxy.yoga.business.dao.model.BusinessStoreApply;
import com.woniuxy.yoga.business.dao.mapper.BusinessStoreApplyMapper;
import com.woniuxy.yoga.business.model.dto.businessstoreapply.StoreApplyAuditDTO;
import com.woniuxy.yoga.business.model.dto.businessstoreapply.StoreApplyDTO;
import com.woniuxy.yoga.business.model.dto.businessstoreapply.StoreApplySelectDTO;
import com.woniuxy.yoga.business.model.dto.businessstoreapply.StoreNotAuditedDTO;
import com.woniuxy.yoga.business.model.exception.BusinessException;
import com.woniuxy.yoga.business.model.exception.BusinessExceptionCode;
import com.woniuxy.yoga.business.model.param.businessstoreapply.AdminStoreApplyAuditParam;
import com.woniuxy.yoga.business.model.param.businessstoreapply.SelectPageAuditedParam;
import com.woniuxy.yoga.business.model.param.businessstoreapply.SelectPageNotAuditedParam;
import com.woniuxy.yoga.business.model.param.businessstoreapply.StoreApplyAddParam;
import com.woniuxy.yoga.business.service.BusinessStoreApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.yoga.commons.core.model.PageInfo;
import com.woniuxy.yoga.commons.core.statedata.BusinessState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商家门店申请表 服务实现类
 * </p>
 *
 * @author 韦用文,刘存益,郎腾霄
 * @since 2023年11月28日
 */
@Service
public class BusinessStoreApplyServiceImpl extends ServiceImpl<BusinessStoreApplyMapper, BusinessStoreApply> implements BusinessStoreApplyService {

    @Autowired
    private BusinessStoreApplyMapper businessStoreApplyMapper;
    @Autowired
    private BusinessStoreMapper businessStoreMapper;
    @Autowired
    private BusinessAccountMapper businessAccountMapper;

    @Autowired
    private BusinessPaymentMapper businessPaymentMapper;

    /**
     * 申请成为平台商家
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StoreApplyDTO addStoreApply(StoreApplyAddParam param) {
        //商家账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(param.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!= BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //查询该商家下所有的申请信息
        List<BusinessStoreApply> storeApplies = businessStoreApplyMapper.selectList(new LambdaQueryWrapper<BusinessStoreApply>().eq(BusinessStoreApply::getAccountId, param.getAccountId()));
        if (storeApplies!=null&&storeApplies.size()!=0) {
            for (BusinessStoreApply storeApply : storeApplies) {
                //若存在待审核的申请 抛异常
                if (storeApply.getCheckState()== BusinessState.STORE_CHECK_STATE_WAIT) {
                    throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_APPLY_STATEERROR);
                }
            }
        }
        //查询该商家下所有的门店信息
        List<BusinessStore> businessStores = businessStoreMapper.selectList(new LambdaQueryWrapper<BusinessStore>().eq(BusinessStore::getAccountId, param.getAccountId()));
        if (businessStores!=null&&businessStores.size()!=0) {
            for (BusinessStore businessStore : businessStores) {
                //若存在没有注销的门店则抛异常
                if (businessStore.getStoreState()!= BusinessState.STORE_STATE_DELETE) {
                    throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_BUSINESS_HASSTORE);
                }
            }
        }
        //新增到数据库中
        BusinessStoreApply storeApply = BeanUtil.toBean(param, BusinessStoreApply.class);
        storeApply.setApplyTime(DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
        storeApply.setCheckState(BusinessState.STORE_CHECK_STATE_WAIT);
        businessStoreApplyMapper.insert(storeApply);
        return BeanUtil.toBean(storeApply,StoreApplyDTO.class);
    }

    /**
     * 平台审核门店申请信息
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public StoreApplyAuditDTO auditStoreApply(AdminStoreApplyAuditParam param) {
        //查询该申请是否存在
        BusinessStoreApply storeApply = businessStoreApplyMapper.selectOne(new LambdaQueryWrapper<BusinessStoreApply>().eq(BusinessStoreApply::getStoreApplyId, param.getStoreApplyId()));
        if (storeApply==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_APPLY_NOTEXITS);
        }
        //查询商家账号是否存在
        BusinessAccount businessAccount = businessAccountMapper.selectById(storeApply.getAccountId());
        if (businessAccount==null) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_NOTEXITS);
        }
        //账号状态是否正常
        if (businessAccount.getAccountState()!=BusinessState.BUSINESS_ACCOUNT_STATE_NORMAL) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_ACCOUNT_STATEERROR);
        }
        //赋值审核人和审核时间
        storeApply.setCheckUser(param.getCheckUser());
        storeApply.setCheckTime(DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
        //若审核状态不符合规范则抛异常
        if (param.getCheckState()!= BusinessState.STORE_CHECK_STATE_PASS&&param.getCheckState()!=BusinessState.STORE_CHECK_STATE_REJECT) {
            throw new BusinessException(BusinessExceptionCode.BUSINESS_EXCEPTION_CODE_CHECK_STATEERROR);
        }
        storeApply.setCheckState(param.getCheckState());
        storeApply.setRejectReason(param.getRejectReason());
        businessStoreApplyMapper.updateById(storeApply);
        //审核通过生成门店信息
        if (param.getCheckState()== BusinessState.STORE_CHECK_STATE_PASS) {
            BusinessStore businessStore = BeanUtil.toBean(storeApply, BusinessStore.class);
            businessStore.setStorePhone(businessAccount.getAccountPhone());
            businessStore.setStoreState(BusinessState.STORE_STATE_DISABLE);
            businessStore.setEnterMoneyState(BusinessState.ENTER_MONEY_STATE_NO_PAY);
            businessStore.setStoreScore(5.0);
            businessStore.setEnterMoney(new BigDecimal(BusinessState.ENTER_MONEY));
            businessStoreMapper.insert(businessStore);
            //生成入驻缴费表
            BusinessPayment businessPayment = new BusinessPayment();
            //雪花算法生成缴费ID
            businessPayment.setPaymentId(new Snowflake(1, 1).nextIdStr());
            businessPayment.setAccountId(businessAccount.getAccountId());
            businessPayment.setPaymentMoney(new BigDecimal(BusinessState.ENTER_MONEY));
            businessPayment.setCreateTime(DateUtil.format(new Date(System.currentTimeMillis()), "yyyy-MM-dd HH:mm:ss"));
            businessPayment.setPaymentState(BusinessState.ENTER_MONEY_STATE_NO_PAY);
            businessPaymentMapper.insert(businessPayment);
        }
        return BeanUtil.toBean(storeApply,StoreApplyAuditDTO.class);
    }

    /**
     * 平台分页查询未审核门店信息
     * @param param
     * @return
     */
    @Override
    public PageInfo selPageNotAudited(SelectPageNotAuditedParam param) {
        LambdaQueryWrapper<BusinessStoreApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStoreApply::getCheckState,BusinessState.STORE_CHECK_STATE_WAIT);
        Page<BusinessStoreApply> page = page(new Page<>(param.getCurrent() == null ? 1 : param.getCurrent(), param.getSize() == null ? 10 : param.getSize()), queryWrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        List<StoreNotAuditedDTO> dtos = BeanUtil.copyToList(page.getRecords(), StoreNotAuditedDTO.class);
        pageInfo.setRecords(dtos);
        return pageInfo;
    }

    /**
     * 分页查询已审核的门店信息
     * @param param
     * @return
     */
    @Override
    public PageInfo selPageAudited(SelectPageAuditedParam param) {
        Page<BusinessStoreApply> page = new Page<BusinessStoreApply>(param.getCurrent()==null||param.getCurrent().equals("")?1:param.getCurrent(),
                param.getSize()==null||param.getSize().equals("")?10:param.getSize());
        LambdaQueryWrapper<BusinessStoreApply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusinessStoreApply::getCheckState,BusinessState.STORE_CHECK_STATE_PASS).or().eq(BusinessStoreApply::getCheckState,BusinessState.STORE_CHECK_STATE_REJECT);
        businessStoreApplyMapper.selectPage(page, queryWrapper);
        PageInfo pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setRecords(BeanUtil.copyToList(page.getRecords(), StoreApplySelectDTO.class));
        pageInfo.setPages(page.getPages());
        return pageInfo;
    }

}
